import BaseForm from './base-form';
import TaskNode from './nodes/task-node';
import LineNode from './nodes/line-node';
import StartNode from './nodes/start-node';
import EndNode from './nodes/end-node';
import ForkNode from './nodes/fork-node';
import CountersignNode from './nodes/countersign-node';
import ToassigneeNode from './nodes/toassignee-node';
import JointNode from './nodes/joint-node';
import CircularNode from './nodes/circular-node';
import BatchtaskNode from './nodes/batchtask-node';
import RandomNode from './nodes/random-node';

import { isArray, isNotEmpty, uuid, isEmpty } from '@jecloud/utils';
export default class Jebpm {
  nodeMaps = new Map();

  constructor(options) {
    /**
     * 工作流信息 (先写死)
     */
    this.jebpm = { id: 'JEBPM', url: 'http://jepaas.com' };
    /**
     * 画布大小
     */
    this.bounds = {
      lowerRight: {
        x: 1485.0,
        y: 700.0,
      },
      upperLeft: {
        x: 0.0,
        y: 0.0,
      },
    };

    /**
     * 资源id (先写死)
     */
    this.resourceId = 'canvas';

    /**
     * 基础信息
     */
    this.properties = new BaseForm(options.properties || {});

    /**
     * 节点数据
     */
    this.childShapes = [];

    // 初始化节点数据
    this.addChildShapes(options.childShapes || []);
  }

  /**
   * 添加子节点
   * @param {*} nodes
   */
  addChildShapes(nodes) {
    //判重
    const nodeData = this.childShapes.filter((item) => item.resourceId == nodes.resourceId);
    if (nodeData.length > 0) {
      return;
    }

    nodes = isArray(nodes) ? nodes : [nodes];
    nodes.forEach((node) => {
      /* if (node.stencil.id == 'line') {
        this.setNodeTarget(node);
      } */
      this.childShapes.push(this._createNode(node));
    });
  }

  _createNode(node) {
    if (node.isModel) return node;
    switch (node.stencil.id) {
      //连线
      case 'line':
        return new LineNode(node);
      //开始
      case 'start':
        return new StartNode(node);

      //结束
      case 'end':
        return new EndNode(node);

      //判断
      case 'decision':
        return new TaskNode(node);

      //任务
      case 'task':
        return new TaskNode(node);

      //分支
      case 'branchGateway':
        return new ForkNode(node);

      //聚合
      case 'aggregationGateway':
        return new ForkNode(node);

      //会签
      case 'countersign':
        return new CountersignNode(node);

      //固定人
      case 'to_assignee':
        return new ToassigneeNode(node);

      //候选
      case 'joint':
        return new JointNode(node);

      //自由
      case 'circular':
        return new CircularNode(node);

      //随机
      case 'random':
        return new RandomNode(node);

      //多人审批
      case 'batchtask':
        return new BatchtaskNode(node);
    }
  }

  /**
   * 数据封装
   */
  dataEncapsulation(cells) {
    this.properties.name = this.properties.processBasicConfig.name;
    //根据目前流程图上的数据,重新组装数据
    const newNodeArray = [],
      LineNodeDatas = [];
    cells.forEach((cell) => {
      //节点对应的数据对象
      const nodeData = this.childShapes.filter((item) => item.resourceId == cell.getId())[0];
      if (isNotEmpty(nodeData)) {
        //如果是线
        if (cell.edge) {
          nodeData.source = [{ resourceId: cell.source && cell.source.getId() }]; //入口
          nodeData.target = [{ resourceId: cell.target && cell.target.getId() }]; //出口
          LineNodeDatas.push(nodeData);
          //普通节点
        } else {
          nodeData.target = [];
          //位置信息
          nodeData.bounds = {
            x: cell.geometry.x,
            y: cell.geometry.y,
            width: cell.geometry.width,
            height: cell.geometry.height,
          };
        }
        newNodeArray.push(nodeData);
      }
    });

    //在根据连线的数据,给普通节点赋值它的出线id
    if (LineNodeDatas.length > 0 && newNodeArray.length > 0) {
      LineNodeDatas.forEach((line) => {
        newNodeArray.forEach((item) => {
          if (item.resourceId == line.source[0].resourceId) {
            item.target.push({ resourceId: line.resourceId });
          }
        });
      });
    }
    this.childShapes = newNodeArray;

    //生成uuid
    if (isNotEmpty(this.properties.oldUuid)) {
      if (this.properties.oldUuid == 'new') {
        this.properties.process_id = uuid();
        this.properties.oldUuid = this.properties.process_id;
      } else {
        this.properties.process_id = this.properties.oldUuid;
      }
    }
    if (isEmpty(this.properties.process_id)) {
      this.properties.process_id = uuid();
    }
  }

  /**
   * 获得节点数据
   * @param {String} id 节点的id
   * @returns 节点的数据对象
   */
  getNodeData(id) {
    const nodeData = this.childShapes.filter((item) => item.resourceId == id) || [];
    if (nodeData.length > 0) {
      return nodeData[0];
    }
    return {};
  }

  /**
   * 删除节点数据
   * @param {Array} ids 节点Id
   * @param {Array} types 节点类型
   */
  removeNodeData(ids, lineNodeDatas) {
    if (ids.length > 0 && this.childShapes.length > 0) {
      this.childShapes.forEach((item, index) => {
        if (ids.indexOf(item.resourceId) != -1) {
          this.childShapes.splice(index, 1);
        }
      });
    }

    //如果节点类型是连线 需要删除入口节点的target值
    if (lineNodeDatas.length > 0) {
      lineNodeDatas.forEach((item) => {
        if (isNotEmpty(item.source)) {
          //找到连线的节点
          const nodeData = this.getNodeData(item.source.getId());
          //删除出线的Id
          nodeData.target.forEach((tar, index) => {
            if ((tar.resourceId = item.id)) {
              nodeData.target.splice(index, 1);
            }
          });
        }
      });
    }
  }

  /**
   * 给节点赋值出线的Id
   * @param {Object} node 线的信息
   */
  setNodeTarget(node) {
    if (isNotEmpty(node.source.resourceId)) {
      const nodeData = this.getNodeData(node.source.resourceId);
      if (isNotEmpty(nodeData)) {
        nodeData.target.push({ resourceId: node.resourceId });
      }
    }
  }

  /**
   *
   * @param {String} id
   */
  setWfId(id, uuid) {
    this.properties.JE_WORKFLOW_PROCESSINFO_ID = id || '';
    if (isNotEmpty(uuid)) {
      this.properties.oldUuid = uuid;
    }
  }

  initData(data, id) {
    this.bounds = data.bounds;
    this.childShapes = data.childShapes;
    this.jebpm = data.jebpm;
    this.nodeMaps = data.nodeMaps;
    this.properties = data.properties;
    this.resourceId = data.resourceId;

    this.loadForm = !this.loadForm;

    this.properties.JE_WORKFLOW_PROCESSINFO_ID = id;
  }

  /**
   *
   * 赋值功能字段
   * @param {Object} funcData 功能信息
   *
   */
  SetFuncData(funcData) {
    if (isNotEmpty(funcData)) {
      for (let item in funcData) {
        this.properties.processBasicConfig[item] = funcData[item];
      }
    }
  }
}
